/**********************************************
                fpc/fpp/fpp2.c
written by IL
edited by CAS

contains the main menu
cari 7/5/4 - change to allow parameters for last 3 marker searchers
**********************************************/
#include "fpp.h"
#include <sys/stat.h>  
#include <malloc.h>
#include <ctype.h>
#include <gtk/gtkwidget.h>   

#define KEYSET PALEBLUE
extern int NewSearchClass;
extern int Zbatch_flag;
extern int autosave_stats;
extern char clientIP[];

extern GtkWidget *ctg_window;   
extern GtkWidget *merge_window1;
extern GtkWidget *merge_window2;
extern GtkWidget *clone_edit_window; 
extern GtkWidget *markerEditWindow; 
extern GtkWidget *help_window; 
extern Graph gsum;
extern void close_ctg_window();
extern void quitCpM();
extern void quitMTP();
extern void free_ctg_layout_mem();
extern int graphQueryOpen();

extern Graph results;
extern void close_results();
extern void bss_display();
extern GtkWidget *bss_window;

extern void save_markers_as_excel();
extern void save_ordered_marker_list();
extern void ZselectMTP();
extern void sequence_window();
extern void clear_listroot();

extern int Num_threads; /* defined in clam/shared.c */
char num_procs[20];  
//#endif

#define graphQuery messQuery

void mergeGSC(), mergeSam(), replaceMarkers(), replaceFW(), replaceSeq();
void mergeMrem(), replaceCtgUserRem();  
void  replaceCtgChrRem();  
void getfpmax(void), clearall(), freelistmem();
void clonesnofp(void);
void displayProj();
void setclassmarker(void);
void recalc_clone_indices();
int save_ace4(void);
void save_fpc_safe(void);
int openandreadfpc();
void pacectgpick();
void listdeleted(void);
void updatecor(void);
void ClamCtgDisplay2(), ClamCtgChr(); 
void setmarkerposaftermerge(void);
void recalccontigs(void);
void markersetzero(void);
void markercorrect(void);
int readfpc(FILE *fpace);
void markersinctgcount(void);
void delmerge(void);
void quitProj(void);
void quitZap(void);
void quitMark(void);
void settime(struct mytime *mytime);
void searchcommand(void);
void searchEngine(void);
void grantaccess(void);
void fpc_unlockit(void);
void projmergerout();
void newproject(void);
void getprefix(void);
void recalcindexes(void);
void gelquit(void);
void killallpreserved(void);
void sortoutmarkersman(void);
void setdefaultflag(void);
void save_as_ace(void);
void save_as_fpc(void);
void save_fpc_in_newfile(void);
void save_clone_sizes(void);
void createorderedlist(void);
void cleancor(void);
void debugmenu(void);
void unattachedclones();
void show_help();

static void mainHelp() {
   show_help("Main Menu","mainmenu");
}
static void docHelp() {
   show_help("Other Documentation","otherdoc");
}
static void overviewHelp() {
printf("\nTo veiw the help, the following must be set:\n");
printf("setenv FPCHELP [location of file FPChelpdoc.htm]\n");
printf("If this is not set, you will be prompt for the location.\n");
   show_help("Overview","overview");
}

/* sness */
/*  */
/* This is needed because the new behaviour of libgraph is to  */
/* put the full filename in filqueryopen(dirName, fileName,...) */
/* and we don't want the suffix. */

void suffixremove(char *file)
{
  int i = 0;
  int slashpos = 0;
  int dotpos = 0;

  /* Find position of last "\" in file */
  while(file[i] != '\0' && (i < MAXPATHLEN)) {
	if (file[i] == '/')
	  slashpos = i;
	i++;
  }
  
  i = slashpos;
  /* Find position of last "." in file */
  while(file[i] != '\0' && (i < MAXPATHLEN)) {
	if (file[i] == '.')
	  dotpos = i;
	i++;
  }

  /* Set that position to "\0" */
  if (dotpos > slashpos)
	file[dotpos] = '\0';
}

static void searchclear(), searchreset();
/**************************************************************
               DEF: boxAceCrash
in graphsub.c and graphxlib.c
ge problesm with boxes, this is called for user friendly crash
***************************************************************/
#ifdef AGCoL
#include <sys/core.h>
#include <signal.h>
#endif

void boxAceCrash(char *msg, int k)
{
    fprintf(stderr,"%s: Offending box is %d\n",msg, k);
#ifdef AGI
    if(messQuery("Do you wish to save before crashing? "))
        save_fpc_safe();
    fpc_unlockit();
    if(messQuery("Do you want a core dump?")){
       raise(SIGQUIT);
    }
#else
	/* sness */
    /*if(graphQuery("Do you wish to save before crashing? ")) */
    if(messQuery("Do you wish to save before crashing? "))
      save_fpc_safe();
    fpc_unlockit();
#endif
    exit(0);
}
/************************************************************
               DEF: destroyMain
************************************************************/
void destroyMain()
{
  BOOL finished = TRUE;

  if(update){ /* if file has been changed */
    finished = FALSE;
    if(messQuery("Quit without saving."))
      finished = TRUE;
    else if(messQuery("Save and Quit.")){
      save_fpc_safe();
      finished = TRUE;
    }
  }
  if(finished){
     if (writeaccess)
        grantaccess(); /* cari 12/24/03 - not releasing lock on Quit */
     if (Zbatch_flag) {
        fflush(stdout); fflush(stderr);
     }
     else printf("Exiting FPC\n");
     exit(0);
  }
}

BOOL filCheck (char *name, char *spec)
{
  struct stat status ;

  if (!spec) /* so filName returns full file name (for error messages) */
    return TRUE ;
                                /* directory check */
  if (spec[0] == 'd'  &&
      (stat (name, &status) || !(status.st_mode & S_IFDIR)))
    return 0 ;
  return 1;
}

/* WN 04/04 gtk window ptrs were not getting initialized to 0 */
void init_window_ptrs()
{
    bss_window = NULL;
    ctg_window = NULL;
    merge_window1 = NULL;
    merge_window2 = NULL;
    clone_edit_window = NULL;
    markerEditWindow = NULL;
    help_window = NULL;
}

void clearallmaps()
{
  clearall();
  if(graphActivate(gselected)) graphDestroy(); /* select options */
  if(graphActivate(gselected2)) graphDestroy(); /* edit options */
  if(graphActivate(gconfig)) graphDestroy();  /* contig config */
  if(graphActivate(g7)) graphDestroy(); /* clone Text */
  if(graphActivate(gmarker)) graphDestroy(); /* marker text */
  if(graphActivate(gmarkerpopup)) graphDestroy(); /* marker text */
  if(graphActivate(g2)) graphDestroy();
  if(graphActivate(g3)) graphDestroy();
  if(graphActivate(g4)) graphDestroy();
  if(graphActivate(gcomment)) graphDestroy();
  if(graphActivate(gsearch)) graphDestroy();
  if(graphActivate(gpace)) graphDestroy();
  if(graphActivate(gsubmit)) graphDestroy();
  if(graphActivate(gCtgChr)) graphDestroy();
  if(graphActivate(gCtgRmk)) graphDestroy();
  if(graphActivate(gsum)) graphDestroy();

  if(graphActivate(results)) close_results(NULL,NULL,NULL);
  if(bss_window!=NULL) gtk_widget_destroy(bss_window);
  if(ctg_window!=NULL) gtk_widget_destroy(ctg_window);
  if(merge_window1!=NULL) gtk_widget_destroy(merge_window1);
  if(merge_window2!=NULL) gtk_widget_destroy(merge_window2);
  if(clone_edit_window != NULL) gtk_widget_destroy(clone_edit_window);
  if(markerEditWindow != NULL) gtk_widget_destroy(markerEditWindow);
  if(help_window!=NULL) gtk_widget_destroy(help_window);
  init_window_ptrs();

  quitCpM();
  gelquit();
  quitProj(); /* project window */
  delmerge();
  fpquit();
  quitMTP();
  killallpreserved();
  quitZap();
  currentctg = currentclone = currentmarker = -1;
  gelhigh = fphigh = -1;
}

void markerfreemem()
/* This subroutine removes all the markerclone memory. */ 
{
  struct markerclone *mpclone,*mpclonetemp;
  int max;
  int i;
  struct markerctgpos *pos,*postemp;

  if(!markerdata)
    return;
  max = arrayMax(markerdata);

  for(i=0;i<max;i++){

    pos= arrp(markerdata,i,MARKER)->pos;
    while(pos !=NULL){
      postemp = pos;
      pos = pos->next;
      messfree(postemp);
    }
    mpclone = arrp(markerdata,i,MARKER)->nextclone;
    while(mpclone != NULL){
      mpclonetemp = mpclone;
      mpclone = mpclone->nextclone;
      messfree(mpclonetemp);
    }
  }
  if(!arrayDestroy(markerdata))
    printf("markerdestroy failed\n");
  
}

/* #define freeupper(x) (FREE_UPPER[x & 0xff])*/

void displaymess(char *text)
{
  printf("%s\n",text);
}

void message_box(int argc, char **argv)
{
  int i;
  FILE *fpace; 
  int j=0,k=0,leen;
  char str1[60];
  BOOL found = FALSE,opened = FALSE,first=TRUE;
  struct list *p=NULL;
  int c;

  displaymess("****************************************************************");
  sprintf(str1,"                FPC V%s  %s",VERSION, LASTMOD);
  displaymess(str1);
  displaymess("  ");
  displaymess("Author: C.A. Soderlund  Email: cari@agcol.arizona.edu");
  displaymess("Arizona Genomics Computational Laboratory");
  displaymess("BIO5 Institute, University of Arizona, Tucson, AZ");
  displaymess("  ");
  displaymess("Major contributions by F. Engler and W. Nelson");
  displaymess("See www.agcol.arizona.edu/software/fpc for additional contributions.");
  displaymess("Using the aceDB graphics package [R. Durbin and J. Thierry-Mieg]");
  displaymess("Reference: C.Soderlund et al. 2000. Contigs build with");
  displaymess("fingerprints, markers and FPC V4.7. Genome Research 10:1772-1787.  ");
  displaymess("****************************************************************");

  SHARED_OPTION = 0;	
  SIM_FLAG =0;

  while (1) {
	c = getopt(argc, argv, "sbhrpdt");
	if (c == -1) break;

	switch (c)
	{
	  case 'p':	  	
		SHARED_OPTION = 1;

		if(argv[optind][0] >= '0' && argv[optind][0] <= '9'){ 	
		  strcpy(num_procs, argv[optind]);
		  Num_threads = atoi(num_procs);
		  optind++;
		}
        else {
          fprintf(stderr,"Illegal number of threads %s\n",argv[optind]);
          _exit(0);
        }
		break;
      case 's':
		SIM_FLAG = 1;
		printf ("Simulation of digestion techniques option \n");
		printf ("Remember to load the remarks file \n");
		break;
		
	  default:
		printf ("Illegal option %d\n", c);
		printf ("Legal options: -p <n> -s\n");
		printf (" -p <n> number of processors\n");
		printf (" -s simulation (see www.agcol.arizona.edu for details)\n");
        _exit(0);
        }
  }

  if(SHARED_OPTION)
  {
	printf("Shared memory implementation - %d threads requested\n", Num_threads);
  }
  else
  {
	printf("Serial implementation \n");
  }

  if(argc - optind >= 1){
    strcpy(fileName,argv[optind]);
    i = strlen(fileName)-1;
    if (fileName[i]=='.') fileName[i] = '\0';
    else if (fileName[i-3]=='.' && fileName[i-2]=='f' && fileName[i-1]=='p' 
           && fileName[i]=='c') fileName[i-3] = '\0';
  
    leen = strlen(fileName);
    if(leen >= 1 ){
      i = leen;
      found = FALSE;
      while(i>0 && !found){
	if(fileName[i] == '/'){
	  found = TRUE;
	  j = i;
	}
	else
	  i--;
      }
      if(found){
	strncpy(dirName,fileName,j);
	for(i=j+1;i<leen;i++){
	  fileName[k++] = fileName[i];
	}
	fileName[k] = '\0';
      }
    }
    opened = TRUE;
    if(strlen(dirName) !=0){
      if((fpace = fopen(messprintf("%s/%s.fpc",dirName, fileName),"r")) == NULL ){
	opened = FALSE;
	displaymess("******************************************");
	sprintf(str1,"File %s/%s.fpc does not exist. No Data Loaded.",dirName,fileName);
	displaymess(str1);
	strcpy(fileName,"");
      }
    }
    else{
      if((fpace = fopen(messprintf("%s.fpc",fileName),"r")) == NULL ){
	opened = FALSE;
	displaymess("******************************************");
	sprintf(str1,"File %s/%s.fpc does not exist. No Data Loaded.",dirName,fileName);
	displaymess(str1);
	strcpy(fileName,"");
      }
    }
    displaymess("Loading project:");
    if(opened && readfpc(fpace)) {
      dataloaded = TRUE;
      if(argc - optind >= 2){
	currentctg = atoi(argv[optind+1]);
	if(currentctg <= max_contig){
	  if(currentctg > 0 && contigs[currentctg].count >0){
	    ctgdisplay(currentctg);
	    lastpicked = lastdbclicked = currentctg;
	    texthigh.ctg = currentctg;
	  }
	  else 
	    currentctg = 0;
	}
	else
	  currentctg = 0;
      }
    } else fileName[0] = '\0';
  }
  if(dataloaded){
    strcpy(chsearchglob,"");
    first = TRUE;
    for(i=1;i<=max_contig;i++){
      if(contigs[i].ctg != 0){
	if(first){
	  listroot  = (struct list *)messalloc((sizeof(struct list)));	
	  listroot->next = NULL;
	  p = listroot;
	  p->index = i;
	  first = FALSE;
	}
	else{
	  p->next = (struct list *)messalloc((sizeof(struct list)));	
	  p=p->next;
	  p->index = i;
	}
      }
    }
    if(!first) p->next = NULL;
    classctg = CTGCLASS;
    searchtype = 1;
    getlist();
  }
  menu_main();
}

void mainpick(int box, float x, float y)
{
  if(box == 1){
    if(texthigh.project == 1)
      displayProj();
    else{
      texthigh.project =1;
      menu_main();
    }
  }
  else if(box != 0)
    graphTextEntry(chsearchglob, NAME_SZ , 0, 0,searchclass);      
}

void none(void);

void clseaname()
{
  searchtype = SeaName;
  menu_main();
}

void clseaaftmod()
{
  searchtype = SeaDateModAfter;
  menu_main();
}

void clseaaftcre()
{
  searchtype = SeaDateCreateAfter;
  menu_main();
}

void markseaname()
{
  searchtype = SeaName;
  menu_main();
}

void markseaaftmod()
{
  searchtype = SeaDateModAfter;
  menu_main();
}

void markseaaftcre()
{
  searchtype = SeaDateCreateAfter;
  menu_main();
}

void marksearem()
{
  searchtype = SeaRemark;
  menu_main();
}

void clsearem()
{
  searchtype = SeaRemark;
  menu_main();
}

void clgeltype()
{
  searchtype = SeaGel;
  menu_main();
}
void clseactg()
{
  searchtype = SeaCtg;
  menu_main();
}
static void nooperation() {}

/**************************************************************
                   DEF: menu_main
****************************************************************/
void menu_main()
{
  BOOL new = FALSE;
  int searchbox=0,i=0,ctgbox,clobox,newbox,marbox;
  int box;

  static MENUOPT clonesearchMenu[]={
   { clseaname,"Name"},
   { clseactg,"Contig"},
   { clgeltype,"Gel Identifier"},
   { clseaaftmod,"After Mod Date"},
   { clseaaftcre,"After Create Date"},
   { clsearem,"Remark"},
   { unattachedclones, "Singletons"},
   { searchcommand,"Search menu"},
   { 0, 0 } };
  static MENUOPT markersearchMenu[]={
   { markseaname,"Name"},
   { markseaaftmod,"After Mod Date"},
   { markseaaftcre,"After Create Date"},
   { marksearem,"Remark"},        
   { searchcommand,"Search menu"},
   { 0, 0 } };
  static MENUOPT fileMenu[]={
   { replaceMarkers,"Replace markers (fw & seq)"},
   { replaceFW,"Replace framework"},
   { replaceSeq,"Replace sequence status"},
   { mergeSam,"Merge markers"},
   { mergeGSC,"Merge clone remarks"},      
   { mergeMrem,"Merge marker remarks"},       
   { replaceCtgUserRem,"Replace contig user remarks"},       
   { replaceCtgChrRem,"Replace contig chromosome remarks"},       
   { nooperation, " "},
   { save_fpc_in_newfile,"Save FPC as ..."},
   { save_as_fpc,"Save Contig as FPC"},
   { nooperation, " "},
   { save_markers_as_excel,"Save Markers as Excel"},
   { save_ordered_marker_list,"Save ordered marker list"}, /* fred 4/14/03*/
   { save_clone_sizes,"Save clone sizes"}, /* cari 1mar04*/
   /*{ pacectgpick,"Save Sequenced contigs"}, cari 8may05 - obsolete */
   { save_as_ace,"Save as Ace"},
   { nooperation, " "},
   {  grantaccess,"(Un)/Lock write access"},
   {  nooperation, " "},
   {  newproject,"Create new project"},
   { nooperation,""},
   { debugmenu,"Check Cor"},
   { 0, 0 }} ;
  static MENUOPT helpMenu[]={
    {overviewHelp,"Overview"},
    {docHelp,"Other documentation"},
    {mainHelp, "Main Menu Functions"},
    { 0, 0 }} ;
   
  static char title[100];

  static MENUOPT menu2[] = {
    { destroyMain, "Quit"},
    { graphPrint, "Print Screen"}, 
    { 0, 0 } };
  float line = 1.0;

  if (Zbatch_flag) return;

  if(graphActivate(gstart)){
    graphClear();
    new = FALSE;
  }
  else{
    if (SHARED_OPTION)
      sprintf(title,"FPC V%s Main Menu %d Threads",VERSION, Num_threads);
    else
      sprintf(title,"FPC V%s Main Menu",VERSION);
                               /* x y w h */
    gstart = graphCreate (TEXT_FIT,title,.2,.2,.36,.30) ; 
    graphMenu (menu2) ;
    graphRegister(PICK,mainpick);
    new =TRUE; 
  }

  line = 1.0;
  graphText("Project: ",2.0,line);
  newbox = graphBoxStart();
  i = graphTextFormat(BOLD);
  graphText(fileName,13.0,line);
  i = graphTextFormat(i);
  graphBoxEnd();
  if(writeaccess)
    graphText("WRITE LOCKED",15.0+strlen(fileName),line);
  if(texthigh.project != 0 )
    graphBoxDraw(newbox,WHITE,BLACK);
  
  line += 2.0;
  graphText("Class: ",2.0,line);
  ctgbox = graphButton("Contigs", setclassctg, 11.0, line);
  clobox = graphButton("Clones", setclassclone, 21.0, line);
  marbox = graphButton("Markers",setclassmarker, 30.0, line);
  if(classctg == CTGCLASS){
    graphBoxDraw(ctgbox,BLACK,KEYSET);
    graphBoxDraw(clobox,BLACK,WHITE);
    graphBoxDraw(marbox,BLACK,WHITE);
  }
  else if(classctg == CLONECLASS){
    graphBoxDraw(clobox,BLACK,KEYSET);
    graphBoxDraw(ctgbox,BLACK,WHITE);
    graphBoxDraw(marbox,BLACK,WHITE);
  }
  else if(classctg == MARKERCLASS){
    graphBoxDraw(marbox,BLACK,KEYSET);
    graphBoxDraw(ctgbox,BLACK,WHITE);
    graphBoxDraw(clobox,BLACK,WHITE);
  }
  line += 2.5;
  
  if (searchtype <1 || searchtype > lastSea) {
        printf("Searchtype %d\n",searchtype);
        searchtype=1;
  }
  graphText("Search:",2.0,line);
  graphText(searchname[searchtype],10.0,line);
  if (searchtype<=lastCloneInputSea || searchtype > lastCloneSea) 
    searchbox = graphTextEntry(chsearchglob, NAME_SZ,
         strlen(searchname[searchtype])+12, line,searchclass);      

  line += 2.5;
  box = graphButton("Search Commands ...",searchcommand,2.0,line);
  if(classctg == CLONECLASS)
    graphBoxMenu(box,clonesearchMenu);
  else if(classctg == MARKERCLASS)
    graphBoxMenu(box,markersearchMenu);
  box = graphButton("Clear",searchclear,24.0,line);
  box = graphButton("Reset",searchreset,32.0,line);

  line += 2.5;
  i = graphButton("File...",none,2.0,line);
  graphBoxMenu(i,fileMenu);
  graphButton("Configure",setdefaultflag,14.0,line);
  graphButton("Clean Up",clearallmaps,26.0,line);

  line += 2.5;
  i = graphButton("Save .fpc",save_fpc_safe,2.0,line);
  i = graphButton("Load .fpc",loadfile,14.0,line);
  graphButton("Update .cor",updatecor,26.0,line);
  line += 2.5;

  graphButton("Main Analysis",ClamCtgDisplay2,7.0,line);
  graphButton("Ctg->Chr",ClamCtgChr,23.0,line);

  line += 2.5;
#ifdef WITH_SEQTRACK
  graphButton("Quit",destroyMain,2.0,line);
  i = graphButton("Help...",overviewHelp,8.0,line);
  graphBoxMenu(i,helpMenu);
  graphButton("BSS",bss_display,22.0,line); 
  graphButton("MTP",ZselectMTP,27.0,line);
  graphButton("Draft",sequence_window,32.0,line);
#else

  graphButton("Quit",destroyMain,11.0,line);
  i = graphButton("Help...",overviewHelp,17.0,line);
  graphBoxMenu(i,helpMenu);
  graphButton("BSS",bss_display,26.0,line); 
  graphButton("MTP",ZselectMTP,31.0,line);
#endif

  if(new){
    graphRedraw();
    graphStart(gstart);
  }
  else
    graphRedraw();
}

/*****************************************************
           remove_old_project
must unlock before getting new dirName, so unlock is not in here.
***************************************************/
void remove_old_project()
{
int i;
  clearallmaps(); /* does a clearall */
  displaymess("Removing old project");
  quitMark();
  markerfreemem();
  clonefreemem();
  if(!arrayDestroy(acedata))
     printf("arraydestroy failed\n");
  if(bands){
    if(!arrayDestroy(bands))
      printf("arrayDestroy failed (bands)\n");
  }
  if(filterdata)        /* 12may99 bugFIX */
      arrayDestroy(filterdata);
  filterdata = 0;
  Proj.filterfile[0] = '\0';

  ctgfreemem();
  root = NULL;
  free(contigs);
  contigs = NULL;

  free_ctg_layout_mem();   /*fred 4/15/03*/

/* reset globals */
  fphigh = gelhigh = -1;
   clhigh = NULL;
   deletefp = FALSE;
   fpmove = FALSE;
   fpflag = FALSE;
   currentctg = -1;
   currentclone = -1;
   highmark = -1;
   highremark = -1;  /*fred 4/22/03*/
   highseq = 0;
   currentmarker = -1;
   for(i=0;i<FPMAX;i++){
     cloneindex[i] = -1;
     clonefpindex[i] = indexbox[i] = 0;
   }
   newctg = TRUE;
   strcpy(chsearchglob,"");
   lastctg = page = ctgmax =0;
   max_contig = 0;
   freelistmem();
}
/*****************************************************************
                     DEF:  loadfile
*****************************************************************/
void loadfile()
{
  int stat;
  FILE *fpace;

  if(update){	
	/* sness */
	/*    if(graphQuery("Load new without saving old.")){ */
    if(messQuery("Load new without saving old.")){
      update = FALSE;
    }
	/* sness */
    /*else if(graphQuery("Save existing project and load new.")){ */
    else if(messQuery("Save existing project and load new.")){
      save_fpc_safe();
      update = FALSE;
    }
  }
  if(!dataloaded){
      displaymess("Loading project:");
      stat = openandreadfpc(); 

      /*efriedr*/
      if(stat>0){
         if(graphActivate(results)) close_results(NULL,NULL,NULL);
         if(bss_window!=NULL) gtk_widget_destroy(bss_window);
      }
  }
  else {
       /* need original dirName for unlock. Can't use temps in filqueryopem.
          I don't understand. Just don't change this. */
     if (writeaccess) 
        grantaccess();
     fpace = (FILE *)graphQueryOpen(dirName, fileName, "fpc","r","Choose project to load");
	 /* sness */
	 suffixremove(fileName);
     if(fpace!=0){  
        remove_old_project(); /* need old dirName to remov lock */
	stat = readfpc(fpace);
     }
     else{
	printf("WARNING: New Project Not Loaded. Project %s Retained\n", fileName);
	stat = -1;
      }
   }
   if(stat>0){
      dataloaded = TRUE;
      classctg = CTGCLASS;
      searchtype = 1;
      getlist();
      menu_main();
      /* This needs to be here instead of in clearallmaps()
       * for some reason.*/ 
      if(ctg_window!=NULL) gtk_widget_destroy(ctg_window);
   }
}

/***************************************************************
                DEF: searchclass
Called when user hits carriage return after typing in yellow Main box
**********************************************************/
void searchclass(char *temp)
{
  if(dataloaded){    
    /*strcpy(chsearchglob,temp); WMN: copies to itself, apparently needlessly */
    searchEngine(); /* in getlist.c */
  }
}
/***************************************************************
                DEF: searchclear
Clear button
**********************************************************/
static void searchclear(char *temp)
{
  strcpy(chsearchglob,""); 
  menu_main();
}
/***************************************************************
                DEF: searchreset
Reset button
**********************************************************/
static void searchreset()
{
  getlist();
  displaykeyset(1);
}




/******************************************************
             DEF: setclassctg
Contig Kyeset button selected
*******************************************************/
void setclassctg()
{    

  if(!dataloaded) {
	displaymess("No FPC file has been loaded.");
        return;
  }


  if(max_contig==0) {
	displaymess("No contigs Exist yet. Therefore cannot set Keyset to contigs");
        return;
  }

  if (classctg == SEQCLASS) {
    clear_listroot();
  }

  if(classctg != CTGCLASS) {
	classctg = CTGCLASS;
        if (searchtype!=1) {
	  searchtype = 1;
          strcpy(chsearchglob,""); 
        }
        lastpicked = currentctg;
	if(graphActivate(gsearch)) graphDestroy();
        NewSearchClass=1;
  }
  else {
        searchEngine();
	/*graphPop();  fred 3/5/03*/
  }
  menu_main();
}

/******************************************************
             DEF: setclassclone
Clone Kyeset button selected
*******************************************************/
void setclassclone()
{
  if(!dataloaded) {
	displaymess("No FPC file has been loaded.");
        return;
  }

  if (classctg == SEQCLASS) {
    clear_listroot();
  }

  if(classctg != CLONECLASS){
      if (!(searchtype <= lastCloneSea)) {
          searchtype = 1;
          strcpy(chsearchglob,""); 
      }
      lastpicked = clonedisplayed;
      classctg = CLONECLASS;
      if(graphActivate(gsearch)) graphDestroy();
      NewSearchClass=1;
  }
  else{
      searchEngine();
      graphPop();
  }
  menu_main();
}

/******************************************************
             DEF: setclassmarker
Marker Keyset button selected
*******************************************************/
void setclassmarker()
{
  if(!dataloaded) {
	displaymess("No FPC file has been loaded.");
        return;
  }
  if (markerdata==NULL || arrayMax(markerdata)==0) {
      displaymess("This project contains no Markers");
      return;
  }

  if (classctg == SEQCLASS) {
    clear_listroot();
  }

  if(classctg != MARKERCLASS){
      if (!(searchtype<=lastGeneralSea || searchtype>=SeaMultCtg ||
          searchtype==SeaNoCtg || searchtype==Sea10Clones || searchtype==SeaType)){
          searchtype = 1;
          strcpy(chsearchglob,""); 
      }
      lastpicked = markerdisplayed;
      classctg = MARKERCLASS;
      NewSearchClass=1;
      if(graphActivate(gsearch)) graphDestroy();
  }
  else{
      searchEngine();
      graphPop();
  }
  menu_main();
}
